package com.ly.web.controller.system;

import java.util.List;
import java.util.Set;

import com.ly.common.constant.HttpStatus;
import com.ly.common.constant.UserConstants;
import com.ly.common.core.domain.model.RegisterUser;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.StringUtils;
import com.ly.framework.web.service.WxLoginService;
import com.ly.system.service.ISysUserService;
import com.ly.web.core.utils.Jcode2SessionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ly.common.constant.Constants;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.core.domain.entity.SysMenu;
import com.ly.common.core.domain.entity.SysUser;
import com.ly.common.core.domain.model.LoginBody;
import com.ly.common.core.domain.model.LoginUser;
import com.ly.common.utils.ServletUtils;
import com.ly.framework.web.service.SysLoginService;
import com.ly.framework.web.service.SysPermissionService;
import com.ly.framework.web.service.TokenService;
import com.ly.system.service.ISysMenuService;

/**
 * 登录验证
 * 
 * @author sfli
 */
@Api("用户注册、登陆")
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private WxLoginService  wxLoginService;
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 登录方法
     *
     * @param code 登录信息
     * @return 结果
     */
    @ApiOperation("微信登陆")
    @PostMapping("/wxlogin/{code}")
    public AjaxResult wxLogin(@PathVariable("code") String code)
    {
        AjaxResult ajax = AjaxResult.success();

        // 生成令牌
        String token = wxLoginService.login(code);
        if("error".equals(token)){
            return ajax.error(HttpStatus.UNAUTHORIZED, "获取授权失败，请重新登陆");
        }
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 注册方法
     *
     * @param registerUser 注册信息
     * @return 结果
     */
    @PostMapping("/register")
    public AjaxResult register(@Validated @RequestBody RegisterUser registerUser)
    {
        SysUser user = new SysUser();
        user.setUserName(registerUser.getUserName());
        user.setPhonenumber(registerUser.getPhonenumber());
        user.setEmail(registerUser.getEmail());
        user.setWx(registerUser.getWx());
        user.setNickName(registerUser.getNickName());
        user.setPassword(registerUser.getPassword());
        user.setAvatar(registerUser.getAvatar());
        user.setSex(registerUser.getSex());
        if ( UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxResult.error("注册'" + user.getUserName() + "'失败，账号已存在");
        }
        else if ( StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("注册'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("注册'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getWx())
                && UserConstants.NOT_UNIQUE.equals(userService.checkWxUnique(user)))
        {
            return AjaxResult.error("注册'" + user.getUserName() + "'失败，微信账号已存在");
        }
        user.setUserType(UserConstants.USER_TYPE_MOBILE);
        user.setStatus("0");
        user.setCreateBy("register");
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        userService.insertUser(user);
        return AjaxResult.success();
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}
